package script.v1.didiCallback

import org.apache.commons.lang.StringUtils
import org.apache.http.HttpEntity
import org.apache.http.NameValuePair
import org.apache.http.client.HttpClient
import org.apache.http.client.entity.UrlEncodedFormEntity
import org.apache.http.client.methods.CloseableHttpResponse
import org.apache.http.client.methods.HttpGet
import org.apache.http.client.methods.HttpPost
import org.apache.http.client.utils.URIBuilder
import org.apache.http.impl.client.HttpClients
import org.apache.http.message.BasicNameValuePair
import org.apache.http.util.EntityUtils
import script.GlobalValues

import javax.servlet.http.HttpServletRequest
import javax.servlet.http.HttpSession
/**
 * 通知回调
 * Created by wb-lj240895 on 2016/12/14.
 */
public class NoticeCallback {
    //private static final Logger logger = LoggerFactory.getLogger(NoticeCallback.class);

    private static final String CALLBACK_URL = "open/didi/notify.json";
    private static final String PAY_CALLBACK_URL = "open/didi/pay/pay_notify.json";

    /**
     * 支付回调接口
     * @see script.v1.didiCallback.PayNotifyRequest 支付回调接口字段  若需修改请更改此类
     * @param url
     * @param request
     * @return
     */
    public String handPayNotify(String url, PayNotifyRequest request) {

        if (StringUtils.isNotBlank(url) && request != null) {
            URIBuilder uriBuilder = new URIBuilder(url + PAY_CALLBACK_URL);
            uriBuilder.addParameter("order_id", request.getOrderId());
            uriBuilder.addParameter("callback_info", request.getCallbackInfo());
            uriBuilder.addParameter("client_id", "195939");
            uriBuilder.addParameter("client_secret", "alibaba-client-secret-mock");
            uriBuilder.addParameter("normal_distance", String.valueOf(request.getNormalDistance()));
            uriBuilder.addParameter("pay_time", String.valueOf(System.currentTimeMillis()));

            uriBuilder.addParameter("timestamp", String.valueOf(System.currentTimeMillis()));
            uriBuilder.addParameter("status", String.valueOf(request.getStatus()));
            uriBuilder.addParameter("total_price", String.valueOf(request.getTotalPrice()));

            uriBuilder.addParameter("sign", "alibaba");
            // uriBuilder.addParameter("sign", request.getSign());
            String result = callbackNotifyGet(uriBuilder)
            if (StringUtils.isNotBlank(result)){
                return result
            }else {
                return null;
            }
        }else {
            //logger.error("回调url不能为空{}", url);
            return null;
        }
    }

    /**
     * 通知回调接口
     * @see script.v1.didiCallback.NotifyRequest 通知回调接口字段  若需修改请更改此类
     * @param url
     * @param request
     * @return
     */
    public String handNotify(String url, NotifyRequest request) {



        if (StringUtils.isNotBlank(url) && request != null) {

            HttpClient client = HttpClients.createDefault();
            HttpPost post = new HttpPost(url + CALLBACK_URL);
            List<? extends NameValuePair> parameters = new ArrayList<NameValuePair>();
            parameters.add(new BasicNameValuePair("client_id","195939"));
            parameters.add(new BasicNameValuePair("client_secret","alibaba-client-secret-mock"));
            parameters.add(new BasicNameValuePair("timestamp",String.valueOf(System.currentTimeMillis())));
            parameters.add(new BasicNameValuePair("sign","alibaba"));

            parameters.add(new BasicNameValuePair("order_id",request.getOrderId()));
            parameters.add(new BasicNameValuePair("notify_type",String.valueOf(request.getNotifyType())));
            parameters.add(new BasicNameValuePair("notify_desc",request.getNotifyDesc()));
            HttpEntity entity = new UrlEncodedFormEntity(parameters, "utf-8");

            post.setEntity(entity);

            CloseableHttpResponse response = client.execute(post);
            int statusCode = response.getStatusLine().getStatusCode();
            //回调成功
            if (statusCode >= 200 && statusCode < 400) {
                HttpEntity entitya = response.getEntity();
                String res = EntityUtils.toString(entitya, "utf-8");
                return res;
            } else {
                //logger.error("回调失败，目标服务器错误", response);
                return null;
            }

        }else {
            //logger.error("回调url不能为空{}", url);
            return null;
        }
    }


    /**
     * get方式回调
     * @param builder
     * @return
     */
    private String callbackNotifyGet(URIBuilder builder) {
        if (builder != null) {
            HttpClient client = HttpClients.createDefault();
            String params = builder.build();
            //logger.info("get request,params:{}", params);

            HttpGet httpGet = new HttpGet(params);
            CloseableHttpResponse response = client.execute(httpGet);
            int statusCode = response.getStatusLine().getStatusCode();
            //回调成功
            if (statusCode >= 200 && statusCode < 400) {
                HttpEntity entity = response.getEntity();
                String res = EntityUtils.toString(entity, "utf-8");
                return res;
            } else {
                //logger.error("回调失败，目标服务器错误", response);
                return null;
            }

        } else {
            //logger.error("回调urlBuilder为空,{}", builder);
            return null;
        }
    }
    /**
     * 从session中获取当前callbackurl
     * @param request
     * @return
     */
    public String getCallbackUrlFromRequest(HttpServletRequest request){
        HttpSession session = request.getSession();
        if (session != null){
            Object callback = session.getAttribute(GlobalValues.FIELD_NAME_CALLBACK_URL);
            if (callback != null){
                String callbackUrl = URLDecoder.decode(String.valueOf(callback),"utf-8");
                return callbackUrl;
            }
        }
        return null;
    }
    public String getCallbackUrlFromRequest(HttpServletRequest request,boolean fromSession){
        if (fromSession){
            return getCallbackUrlFromRequest(request);
        }
        //v1 下的接口返回访问时的地址
        System.out.println(JSONObject.fromObject(request).toString());
        int port = request.getServerPort();
        String ip = request.getRemoteAddr();
        if (port == 80){
            return "http://" + ip + "/";
        }
        return "http://"+ ip + ":" + port + "/";
    }
}